Page({
  data: {
    lastRecommendTime: 0, // 上次推荐时间戳
    careerShow: false,
    careerList: [
      { text: '学生', value: '学生' },
      { text: '教师', value: '教师' },
      { text: '医生', value: '医生' },
      { text: '工程师', value: '工程师' },
      { text: '设计师', value: '设计师' },
      { text: '律师', value: '律师' },
      { text: '销售员', value: '销售员' },
      { text: '自由职业', value: '自由职业' },
      { text: '其他', value: '其他' }
    ],
    sexShow: false,
    sexList: [
      { text: '男', value: '男' },
      { text: '女', value: '女' }
    ],
    ageShow: false,
    ageList: [
      { text: '18岁以下', value: '18岁以下' },
      { text: '18-30岁', value: '18-30岁' },
      { text: '31-45岁', value: '31-45岁' },
      { text: '46岁以上', value: '46岁以上' }
    ],
    budgetShow: false,
    budgetList: [
      { text: '500元以下', value: '500元以下' },
      { text: '500-1000元', value: '500-1000元' },
      { text: '1000-2000元', value: '1000-2000元' },
      { text: '2000元以上', value: '2000元以上' }
    ],
    bodyStateShow: false,
    bodyStateList: [
      { text: '健康', value: '健康' },
      { text: '一般', value: '一般' },
      { text: '较差', value: '较差' }
    ],
    latitude: 0,
    longitude: 0,
    user: '',
    result: '',
    url_token: '',
    text: '',
    loadingModalVisible: '0',
    info: {
      user: '',
      age: '',
      sex: '',
      career: '',
      budget: '',
      bodyState: '',
      toPlace: '',
      likes: '',
      dislike: '',
      his_go: '',
      aitext: ''
    },
    // 天气
    weatherInfo: {
      city: '',
      temp: 0,
      condition: '',
      icon: '',
      windDir: '',
      windScale: '',
      windSpeed: '',
      humidity: '',
      tomorrowMaxTemp: "",
      tomorrowMinTemp: '',
      tomorrowCondition: '',
      tomorrowIcon: '',
      afterdayMaxTemp: '',
      afterdayMinTemp: '',
      afterdayCondition: '',
      afterdayIcon: ''
    },
    timestamp: '',
    timer: ''
  },

  onLoad() {
    this.getUserLocation();
    this.getRecommendUrl();
    this.getWeatherData(); // 获取天气数据
  },

  onShow() {
    this.setData({ user: wx.getStorageSync('user') || '' });
  },

  getRecommendUrl() {
    const db = wx.cloud.database();
    const recommendCollection = db.collection('zyzl_recommend');
    recommendCollection.where({}).get().then(res => {
      if (res.data.length > 0) {
        const recommendInfo = res.data[0];
        const url_token = recommendInfo.url_token;
        const text = recommendInfo.text;
        this.setData({ url_token });
        this.setData({ text });
      } else {
        console.error('未找到数据');
      }
    }).catch(err => {
      console.error('获取数据失败', err);
    });
  },

  getWeatherData() {
    const db = wx.cloud.database();
    db.collection('zyzl_weather').get({
      success: res => {
        if (res.data.length > 0) {
          const weather = res.data[res.data.length - 1]; // 获取最后一个天气数据
          this.setData({
            'weatherInfo.city': weather.city,
            'weatherInfo.temp': weather.temp,
            'weatherInfo.condition': weather.condition,
            'weatherInfo.icon': weather.icon,
            'weatherInfo.windDir': weather.windDir,
            'weatherInfo.windScale': weather.windScale,
            'weatherInfo.windSpeed': weather.windSpeed,
            'weatherInfo.humidity': weather.humidity,
            'weatherInfo.tomorrowMaxTemp': weather.tomorrowMaxTemp,
            'weatherInfo.tomorrowMinTemp': weather.tomorrowMinTemp,
            'weatherInfo.tomorrowCondition': weather.tomorrowCondition,
            'weatherInfo.tomorrowIcon': weather.tomorrowIcon,
            'weatherInfo.afterdayMaxTemp': weather.afterdayMaxTemp,
            'weatherInfo.afterdayMinTemp': weather.afterdayMinTemp,
            'weatherInfo.afterdayCondition': weather.afterdayCondition,
            'weatherInfo.afterdayIcon': weather.afterdayIcon
          });
          console.log('Weather Info:', this.data.weatherInfo);
        }
      },
      fail: err => {
        console.error('获取天气数据失败:', err);
      }
    });
  },

  formSubmit(e) {
    // 检查用户是否已登录
    const user = wx.getStorageSync('user');
    if (!user) {
      wx.showModal({
        title: '提示',
        content: '请先登录',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/my/login/login'
            });
          }
        }
      });
      return;
    }

    const db = wx.cloud.database();
    const orderCollection = db.collection('zyzl_recommandorder');

    // 查询数据库，按时间戳倒序排序，取第一条数据
    orderCollection.where({
      user: user
    }).orderBy('timestamp', 'desc').limit(1).get().then(res => {
      if (res.data.length > 0) {
        const lastRecommendTime = new Date(res.data[0].timestamp).getTime();
        const now = Date.now();
        const elapsedTime = now - lastRecommendTime;
        const remainingTime = 10 * 60 * 1000 - elapsedTime; // 10分钟对应的毫秒数减去已过去的时间

        // 如果距离上次推荐时间不足 10 分钟，则不执行后续操作
        if (elapsedTime < 1000) {
          const remainingMinutes = Math.floor(remainingTime / (1000 * 60));
          const remainingSeconds = Math.floor((remainingTime / 1000) % 60);
          wx.showToast({
            title: '冷却时间还剩 ' + remainingMinutes + ' 分钟 ' + remainingSeconds + ' 秒',
            icon: 'none'
          });
          return;
        }
        // 更新上次推荐时间为获取到的时间戳值
        this.setData({ lastRecommendTime });

        // 继续执行表单提交操作
        const info = e.detail.value;
        if (info.age != '' && info.sex != '' && info.career != '' && info.budget != '' && info.bodyState != '') {
          info.user = user;
          this.getToken(info); // 获取推荐结果
        } else {
          wx.showToast({
            title: '必填项不能为空',
            icon: 'none'
          });
        }
      } else {
        // 新用户执行表单提交操作
        const info = e.detail.value;
        if (info.age != '' && info.sex != '' && info.career != '' && info.budget != '' && info.bodyState != '') {
          info.user = user;
          this.getToken(info); // 获取推荐结果
        } else {
          wx.showToast({
            title: '必填项不能为空',
            icon: 'none'
          });
        }
      }
    }).catch(err => {
      console.error('获取推荐订单数据失败', err);
    });
  },

  getToken(userinfo) {
    // 弹窗确认执行操作
    wx.showModal({
      title: '确认执行',
      content: '是否确认信息正确？',
      success: (modalRes) => {
        if (modalRes.confirm) {
          const user = wx.getStorageSync('user');
          if (!user) {
            wx.showModal({
              title: '提示',
              content: '请先登录',
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '/pages/my/login/login'
                  });
                }
              }
            });
            return;
          }
          // 显示加载弹窗
          this.setData({
            loadModal: true
          });

          wx.request({
            url: this.data.url_token,
            method: "POST",
            header: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            success: res => {
              const access_token = res.data.access_token;
              const url_chat = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + access_token;
              const payload = {
                messages: [{
                  role: "user",
                  content: `现在你是一个来成都旅游的游客，你的个人信息是：[性别: ${userinfo.sex}，年龄：${userinfo.age}岁，职业：${userinfo.career}，预算：${userinfo.budget}，健康状况：${userinfo.bodyState}。] 当前天气情况是：${this.data.weatherInfo.condition}，今天气温：${this.data.weatherInfo.temp}°C，明天气温：${this.data.weatherInfo.tomorrowMaxTemp}°C，后天气温：${this.data.weatherInfo.afterdayMaxTemp}°C。要求在回答里面体现出天气的状况做出的选择，请帮我规划一下旅游路线。并且返回值里面不要有加粗字体和Markdown格式的字体出现`
                }]
              };

              wx.request({
                url: url_chat,
                method: "POST",
                data: payload,
                header: { 'Content-Type': 'application/json' },
                success: res => {
                  console.log(res.data);
                  this.setData({
                    result: res.data.result
                  });
                  this.setData({
                    timestamp: new Date() // 设置时间戳
                  });
                  this.saveRecommendOrder(userinfo, res.data); // 存储推荐订单到云数据库
                  wx.showToast({
                    title: '成功',
                    icon: 'success'
                  });

                  // 关闭加载弹窗
                  this.setData({
                    loadModal: false
                  });

                  // 跳转到推荐页面
                  wx.navigateTo({
                    url: '/pages/tuijian/tuijian?result=' + encodeURIComponent(res.data.result)
                  });
                }
              });
            },
          });
        }
      }
    });
  },

  saveRecommendOrder(userinfo, result) {
    const db = wx.cloud.database();
    const orderCollection = db.collection('zyzl_recommandorder');
    const orderData = {
      user: this.data.user,
      result: result,
      info: userinfo,
      timestamp: this.data.timestamp
    };
    orderCollection.add({
      data: orderData,
      success: res => {
        console.log('存储成功', res);
      },
      fail: err => {
        console.error('存储失败', err);
      }
    });
  },

  getUserLocation(callback) {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        const { latitude, longitude } = res;
        console.log('用户位置信息：', latitude, longitude);
        this.setData({ latitude, longitude });
        if (typeof callback === 'function') {
          callback();
        }
      },
      fail: (error) => {
        console.error('获取用户位置失败：', error);
      }
    });
  },

  // Picker 相关代码（sex, career, budget, etc.）
  sexChange(e) {
    this.setData({ sexShow: false, 'info.sex': e.detail.value });
  },

  sexHide() {
    this.setData({ sexShow: false });
  },

  openSexFn() {
    this.setData({ sexShow: true });
  },

  careerChange(e) {
    this.setData({ careerShow: false, 'info.career': e.detail.value });
  },

  careerHide() {
    this.setData({ careerShow: false });
  },

  openCareerPicker() {
    this.setData({ careerShow: true });
  },

  budgetChange(e) {
    this.setData({ budgetShow: false, 'info.budget': e.detail.value });
  },

  budgetHide() {
    this.setData({ budgetShow: false });
  },

  openBudgetPicker() {
    this.setData({ budgetShow: true });
  },

  ageChange(e) {
    this.setData({ ageShow: false, 'info.age': e.detail.value });
  },

  ageHide() {
    this.setData({ ageShow: false });
  },

  openAgePicker() {
    this.setData({ ageShow: true });
  },

  bodyStateChange(e) {
    this.setData({ bodyStateShow: false, 'info.bodyState': e.detail.value });
  },

  bodyStateHide() {
    this.setData({ bodyStateShow: false });
  },

  openBodyStatePicker() {
    this.setData({ bodyStateShow: true });
  },

  onPullDownRefresh() { },

  onReachBottom() { },

  onShareAppMessage() { },

  goToLastRecommend() {
    const user = wx.getStorageSync('user');
    if (!user) {
      wx.showModal({
        title: '提示',
        content: '请先登录',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/my/login/login'
            });
          }
        }
      });
      return;
    }
    
    wx.navigateTo({
      url: '/pages/search/lasttime/lasttime'
    });
  }
});
